﻿using HslCommunication.ModBus;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using VIA.Integration.Domain;
using VIA.Integration.Domain.Production;
using VIA.Integration.Modbus;
using VIA.Modularity;
using VIA.Presentation;
using VIA.Project.Domain.Services;
using VIA.SiMoJi.Domain.Inspection;
using VIA.SiMoJi.Domain.Vision;
using VIA.VTPlatformService;

namespace VIA.SiMoJi.Domain
{
    [DependsOn(typeof(IntegrationDomainModule))]
    [DependsOn(typeof(VIAVTPlatformServiceModule))]
    public class SiMoJiDomainModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.UseInspectorEngine<Inspector>();
            context.Services.AddSingleton<IVTPlatformManager, VTPlatformManager>();
            context.Services.AddSingleton<IAutoDeleteImage, AutoDeleteImage>();
            context.Services.AddSingleton<IProductionLine, ProductionLine>();
            context.Services.AddSingleton<ICsvStorageService, CsvStorageService>();
            context.Services.AddSingleton<ILocalDatabaseService, LocalDatabaseService>();
            context.Services.AddSingleton<IFilePathBuilder, FilePathBuilder>();
            context.Services.AddSingleton<IImageDetecter, ImageDetecter>();
            context.Services.AddSingleton<ICalcTimeService, CalcTimeService>();
            context.Services.AddSingleton<IZKTEcoFace, ZKTEcoFace>();
            context.Services.AddSingleton<IDataStorageService, DataStorageService>();
        }
        public override async void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var service = context.ServiceProvider;
            var inspector = service.GetService<Inspector>();
            try
            {
                await inspector.InitializeAsync();
                service.GetService<IZKTEcoFace>().Start("192.168.0.50", 8081);
            }
            catch (Exception ex)
            {
                service.GetService<IApplicationLog>().LogError("设备初始化失败:" + ex.Message);
                inspector?.Logger.LogError(ex, ex.Message);
            }
        }
        public override void OnPostApplicationInitialization(ApplicationInitializationContext context)
        {
            var service = context.ServiceProvider;
            var inspector = service.GetService<Inspector>();
            inspector.Refresh();
        }
        public override async void OnApplicationShutdown(ApplicationShutdownContext context)
        {
            var inspector = context.ServiceProvider.GetService<Inspector>();
            inspector.CancelRefresh();
            inspector.SerialPort.Close();
            await inspector.ShutDownAsync();
            var databaseService = context.ServiceProvider.GetRequiredService<ILocalDatabaseService>();
            databaseService.Close();
            base.OnApplicationShutdown(context);
        }

    }
}
